<?php

namespace App\Http\Controllers;

use App\Models\Index;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;

class HomeController extends Controller
{
    //
    public function index(Request $request)
    {
        $pageIndex = $request->get('pageIndex');
        $pageSize = $request->get('pageSize');

        $index = Index::query()
            ->where('type',0)
            ->where('state',1)
            ->orderByDesc('sort')
            ->paginate($pageSize,['*'],'pageIndex',$pageIndex);

        return $this->response($index);
    }

    public function indes(Request $request)
    {
        $pageIndex = $request->get('pageIndex');
        $pageSize = $request->get('pageSize');

        $indes = Index::query()
            ->where('type',1)
            ->where('state',1)
            ->orderByDesc('sort')
            ->paginate($pageSize,['*'],'pageIndex',$pageIndex);

        return $this->response($indes);
    }

    public function upload(Request $request)
    {
        $validator = Validator::make($request->all(),[
            'image' => 'required|mimes:jpeg,png,bmp,gif'
        ]);

        if ($validator->fails()){
            return $this->response([],$validator->errors(),500);
        }

        $hashName = $request->file('image')->hashName();

        $hash_hex = md5($hashName);

        // 16进制表示的字符串一共32字节，表示16个二进制字节。
        // 前16个字符用来第一级求摸，后16个用做第二级
        $hash_hex_l1 = substr($hash_hex, 0, 8);
        $hash_hex_l2 = substr($hash_hex, 8, 8);
        $dir_l1 = hexdec($hash_hex_l1) % 256;
        $dir_l2 = hexdec($hash_hex_l2) % 512;
        $dir = 'uploads/'. $dir_l1. '/' . $dir_l2;

        if( !Storage::disk('public')->exists($dir)) Storage::disk('public')->makeDirectory($dir);

        $file = $request->file('image')->store($dir,'public');

        return $this->response([
            'relative_path' => $file,
            'absolute_path' => Storage::disk('public')->url($file),
        ],'ok');
    }
}
